<template>

  <div class="login-container">

    <div class="nav-line">
      <img src="/images/jh.png" alt="">
      <p>2024年全省公安派出所民警</p>
      <p>职业技能（社区警务）比武</p>
    </div>

    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on"
      label-position="left">

      <div class="title-container">
        <h3 class="title">欢迎登录</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input ref="username" v-model="loginForm.username" placeholder="警号" name="username" type="text" tabindex="1"
          autocomplete="on" />
      </el-form-item>

      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType"
            placeholder="身份证后6位" name="password" tabindex="2" autocomplete="on" @keyup.native="checkCapslock"
            @blur="capsTooltip = false" @keyup.enter.native="handleLogin" />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-tooltip>

       <!-- 验证码组件 -->
      <!-- <el-form-item prop="authcode" class="authcode">

        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>

        <el-input ref="authcode" v-model="loginForm.authcode" placeholder="验证码" name="authcode" type="text" tabindex="3"
          autocomplete="off" />

        <div @click="refreshCode()" class="auth-code">
         
          <SecurityCode :identifyCode="identifyCode"></SecurityCode>
        </div>

      </el-form-item> -->



      <div style="position:relative;">

        <el-row style="display: flex;justify-content: center; align-items: center;" :gutter="10">


          <el-col  :span="16">
            <el-button tabindex="3" :loading="loading" type="primary" style="width:100%;margin-bottom:30px;"
              @click.native.prevent="handleLogin">登录</el-button>
          </el-col>


        </el-row>

      </div>

    </el-form>

  </div>

</template>

<script>
import { validUsername } from '@/utils/validate'
import SecurityCode from '@/components/securityCode'

export default {
  name: 'Login',
  components: { SecurityCode },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入正确的用户名！'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error('密码不能小于5个字符'))
      } else {
        callback()
      }
    }

    const validateAuthcode = (rule, value, callback) => {
      if (value.length == 0) {
        callback(new Error('验证码不能为空'))
      } else if (value != this.identifyCode) {
        callback(new Error('验证码错误'))
      } else {
        callback()
      }
    }

    return {
      loginForm: {
        username: '',
        password: '',
        authcode: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        authcode: [{ required: true, trigger: 'blur', validator: validateAuthcode }],

      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      redirect: undefined,
      otherQuery: {},
      identifyCode: "",//随机组合字符串
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    } else if (this.loginForm.authcode === '') {
      this.$refs.authcode.focus()
    }
    this.refreshCode()
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {

    studentRegister() {
      this.$router.push({ name: 'Register' })
    },

    studentLogin() {
      this.loginForm.username = 'student'
      this.loginForm.password = '123456'
      this.handleLogin()
    },

    adminLogin() {
      this.loginForm.username = 'admin'
      this.loginForm.password = '123456'
      this.handleLogin()
    },
    teacherLogin() {
      this.loginForm.username = 'teacher'
      this.loginForm.password = '123456'
      this.handleLogin()
    },

    onlineGuide() {
      this.$router.push('https://face-files.oss-cn-shenzhen.aliyuncs.com/guide.pdf')
    },

    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (shiftKey && (key >= 'a' && key <= 'z') || !shiftKey && (key >= 'A' && key <= 'Z')) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('提交错误！')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },

    //初始化验证码
    refreshCode() {
      this.inputCode = ''
      this.identifyCode = ""; //输入框置空
      this.makeCode(4); //验证码长度为4
    },
    //随机切换验证码
    makeCode(length) {
      let code = '';
      for (let i = 0; i < length; i++) {
        const r = Math.floor(Math.random() * 36);
        if (r < 10) {
          code += r;
        } else {
          code += String.fromCharCode(r - 10 + 65);
        }
      }
      this.identifyCode = code
      localStorage.setItem('code', code);
      console.log(this.identifyCode);
    },
  }
}
</script>

<style lang="scss">
// $bg: #fefefe;
$light_gray: #fff;
$cursor: #fff;
$dark_gray: #889aa4;
$bg_img: "bg.png";

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      margin-left: 20px;
      width: 90%;
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: #2c2b2b;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $dark_gray inset !important;
        -webkit-text-fill-color: #454545 !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100vh;
  width: 100%;
  overflow: hidden;
  display: flex;
  justify-content: space-between;
  background-image: url("/images/bg/bg_12_16.jpg");
  background-position: center;  
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;

  .nav-line {
    position: absolute;
    top: 12%;
    width: 60%;
    text-align: center;
    color: rgb(255,194,145);
    font-weight: bold;
    font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
    
    p {
      margin: 0;
      font-size: clamp(24px, 5vw, 75px); // 响应式字体大小
    }

    img {
      width: clamp(150px, 20vw, 300px); // 响应式图片大小
    }

    @media screen and (max-width: 768px) {
      width: 90%;
      left: 50%;
      transform: translateX(-50%);
      top: 5%;
    }
  }

  .login-form {
    width: clamp(280px, 90%, 400px); // 响应式宽度
    background-color: #fff;
    padding: 30px;
    border-radius: 20px;
    position: absolute;
    top: 28%;
    right: 10%;

    @media screen and (max-width: 768px) {
      position: relative;
      top: 50%;
      right: auto;
      margin: 20vh auto 0;
      transform: translateY(-50%);
    }

    .el-button {
      width: 60%;
      
      @media screen and (max-width: 480px) {
        width: 80%;
      }
    }
  }

  .tips {
    font-size: 14px;
    color: $dark_gray;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: clamp(30px, 5vw, 50px); // 响应式标题大小
      color: rgb(254,187,134);
      margin: 0px auto 20px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .auth-code {
    position: absolute;
    right: 5px;
    top: 5px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
    
    @media screen and (max-width: 470px) {
      display: none;
    }
  }
}
</style>
